<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" class="search-form">
      <div class="left-section">
        <el-form-item label="项目状态" prop="projectStatus">
          <el-select
            v-model="queryParams.projectStatus"
            placeholder="全部"
            clearable
            style="width: 120px"
          >
            <el-option label="全部" value="" />
            <el-option label="启用" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="queryParams.searchText"
            placeholder="请输入搜索内容"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </div>
      <div class="right-section">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        <el-button type="primary" plain icon="Upload">导入</el-button>
        <el-button type="primary" plain icon="Download" @click="handleExport">导出</el-button>
      </div>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column label="项目编号" align="center" prop="projectId" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="零售价(元)" align="center" prop="retailPrice" />
      <el-table-column label="成本价 (元)" align="center" prop="costPrice" />
      <el-table-column label="创建时间" align="center" prop="creationTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.creationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks" />
      <el-table-column label="项目类别" align="center" prop="projectCategory">
        <template #default="scope">
          <dict-tag :options="sys_project_category" :value="scope.row.projectCategory"/>
        </template>
      </el-table-column>
      <el-table-column label="发票项目" align="center" prop="invoiceItem">
        <template #default="scope">
          <dict-tag :options="sys_qnvoice_item" :value="scope.row.invoiceItem"/>
        </template>
      </el-table-column>
      <el-table-column label="项目状态" align="center" prop="projectStatus">
        <template #default="scope">
          <dict-tag :options="sys_project_status" :value="scope.row.projectStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="会员折扣" align="center" prop="memberDiscount">
        <template #default="scope">
          <dict-tag :options="sys_member_discount" :value="scope.row.memberDiscount"/>
        </template>
      </el-table-column>
      <el-table-column label="单位 (字典)" align="center" prop="unit">
        <template #default="scope">
          <dict-tag :options="sys_unit_ci" :value="scope.row.unit"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:project:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:project:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改检查项目设置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="projectRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目编号" prop="projectId">
          <el-input v-model="form.projectId" placeholder="请输入项目编号" />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="零售价(元)" prop="retailPrice">
          <el-input v-model="form.retailPrice" placeholder="请输入零售价(元)" />
        </el-form-item>
        <el-form-item label="成本价(元)" prop="costPrice">
          <el-input v-model="form.costPrice" placeholder="请输入成本价(元)" />
        </el-form-item>
        <el-form-item label="创建时间" prop="creationTime">
          <el-date-picker clearable
            v-model="form.creationTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="项目类别" prop="projectCategory">
          <el-select v-model="form.projectCategory" placeholder="请选择项目类别" style="width: 100%">
            <el-option label="0" value="0" />
            <el-option label="1" value="1" />
            <el-option label="2" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="发票项目" prop="invoiceItem">
          <el-select
            v-model="form.invoiceItem"
            placeholder="请选择发票项目"
            style="width: 100%"
          >
            <el-option
              v-for="dict in sys_qnvoice_item"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目状态" prop="projectStatus">
          <el-radio-group v-model="form.projectStatus">
            <el-radio
              v-for="dict in filteredProjectStatus"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
          <el-button 
            v-if="title === '修改检查项目设置'"
            type="success" 
            plain 
            style="margin-left: 10px"
            @click="handleEnable"
          >启用</el-button>
          <el-button 
            v-if="title === '修改检查项目设置'"
            type="danger" 
            plain 
            style="margin-left: 10px"
            @click="handleDisable"
          >停用</el-button>
        </el-form-item>
        <el-form-item label="会员折扣" prop="memberDiscount">
          <el-select v-model="form.memberDiscount" placeholder="请选择会员折扣" style="width: 100%">
            <el-option label="启用" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-select v-model="form.unit" placeholder="请选择单位" style="width: 100%">
            <el-option label="启用" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Project">
import { listProject, getProject, delProject, addProject, updateProject } from "@/api/system/project";

const { proxy } = getCurrentInstance();

// 字典数据
const { 
  sys_project_status,
  sys_project_category,
  sys_qnvoice_item,
  sys_member_discount,
  sys_unit_ci 
} = proxy.useDict(
  'sys_project_status',
  'sys_project_category',
  'sys_qnvoice_item',
  'sys_member_discount',
  'sys_unit_ci'
);

// 监听字典数据变化
watch(sys_qnvoice_item, (newVal) => {
  console.log('发票项目字典数据:', newVal);
}, { immediate: true });

const projectList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: null,
    projectName: null,
    retailPrice: null,
    costPrice: null,
    creationTime: null,
    remarks: null,
    projectCategory: null,
    invoiceItem: null,
    projectStatus: null,
    memberDiscount: null,
    unit: null,
    searchText: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

// 过滤后的项目状态选项（排除第一个启用选项）
const filteredProjectStatus = computed(() => {
  return sys_project_status.value?.slice(1) || [];
});

/** 查询检查项目设置列表 */
function getList() {
  loading.value = true;
  // 处理项目状态的查询
  const params = {
    ...queryParams.value,
    projectStatus: queryParams.value.projectStatus === '' ? null : queryParams.value.projectStatus
  };
  
  listProject(params).then(response => {
    projectList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    projectId: null,
    projectName: null,
    retailPrice: null,
    costPrice: null,
    creationTime: null,
    remarks: null,
    projectCategory: null,
    invoiceItem: null,
    projectStatus: null,
    memberDiscount: null,
    unit: null
  };
  proxy.resetForm("projectRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.projectStatus = ''; // 重置时将项目状态设为空（全部）
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加检查项目设置";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getProject(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改检查项目设置";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["projectRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateProject(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProject(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除检查项目设置编号为"' + _ids + '"的数据项？').then(function() {
    return delProject(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/project/export', {
    ...queryParams.value
  }, `project_${new Date().getTime()}.xlsx`)
}

/** 启用按钮操作 */
function handleEnable() {
  proxy.$modal.confirm('是否确认启用该检查项目？').then(() => {
    form.value.projectStatus = "0"; // 设置状态为启用
    submitForm(); // 提交表单
  }).catch(() => {});
}

/** 停用按钮操作 */
function handleDisable() {
  proxy.$modal.confirm('是否确认停用该检查项目？').then(() => {
    form.value.projectStatus = "1"; // 设置状态为停用
    submitForm(); // 提交表单
  }).catch(() => {});
}

// 在组件挂载时获取字典数据
onMounted(() => {
  getList();
  // 检查字典数据是否正确加载
  console.log('所有字典数据:', {
    sys_project_status,
    sys_project_category,
    sys_qnvoice_item,
    sys_member_discount,
    sys_unit_ci
  });
});
</script>

<style scoped>
.search-form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.left-section {
  display: flex;
  align-items: center;
}

.right-section {
  display: flex;
  gap: 8px;
}

.el-form-item {
  margin-bottom: 18px;
  margin-right: 18px;
}

.right-section .el-form-item {
  margin-right: 0;
}
</style>
